﻿using BLL;
using DAL;
using DAL.Dao;
using DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using MqTools;
using Microsoft.AspNetCore.Mvc;
using ExpressManagement.Areas.BackSys.ServiceTools;
using AutoMapper;
using Microsoft.AspNetCore.Mvc.Filters;
using BLL.Interface;
using Microsoft.Extensions.Caching.Memory;
using ExpressManagement.Areas.BackSys.ServiceTools.Redis;
using Microsoft.EntityFrameworkCore;
using DAL.Models.DTO;

namespace ExpressManagement.Areas.BackSys.Controllers
{
    [Area("BackSys")]
    public class BagController : BaseController
    {

        private readonly IBagInfoImpl _impl;
        // GET: Bag

        public BagController(IBagInfoImpl _impl, IMemoryCache _memoryCache, RedisHelper redisHelper, ExpressDBContext _dbContext, IHttpContextAccessor httpContextAccessor, DbContextOptions<ExpressDBContext> _dbContextoptions,
            IMapper mapper, SignalRSender signalRSender)
            : base(mapper: mapper, signalRSender: signalRSender, httpContextAccessor: httpContextAccessor, _memoryCache: _memoryCache, redisHelper: redisHelper, _dbContext: _dbContext, dbContextOptions: _dbContextoptions)
        {
            //if (_impl == null) _impl = new BagInfoImpl();
            this._impl = _impl;
        }

        //public override void OnActionExecuted(ActionExecutedContext context)
        //{

        //    var sess = HttpContext.Session;
        //    if (sess.GetInt32("senderRows") == null)
        //    {
        //        sess.SetInt32("senderRows", 10);
        //    }

        //    if (sess.GetInt32("senderPage") == null)
        //    {
        //        sess.SetInt32("senderPage", 1);
        //    }
        //    if (sess.GetInt32("getterRows") == null)
        //    {
        //        sess.SetInt32("getterRows", 10);
        //    }
        //    if (sess.GetInt32("getterPage") == null)
        //    {
        //        sess.SetInt32("getterPage", 1);
        //    }
        //    if (sess.GetInt32("bagRows") == null)
        //    {
        //        sess.SetInt32("bagRows", 10);
        //    }
        //    if (sess.GetInt32("bagPage") == null)
        //    {
        //        sess.SetInt32("bagPage", 1);
        //    }
        //}
        //public new IActionResult Index()
        //{

        //    return PartialView(_impl.GetList());
        //}


        public IActionResult BagSend()
        {

            switch (LoginType)
            {
                case "用户":

                    return RedirectToAction("Index", "Home");
                case "管理员":
                case "快递员":
                //int? rows = sess.GetInt32("bagRows");
                //int? page = sess.GetInt32("bagPage");
                //if (rows != null && page != null)
                //{
                //    (var totalPages, var data) = _impl.GetList(rows.Value, page.Value);
                //    sess.SetInt32("bagTotalPages", totalPages);
                //    ViewBag.BagList = data;
                //}
                //return PartialView();
                default:
                    break;
            }

            return PartialView();
        }


        private void FillSetAndSaveCache(int totalPages, string dataJson, int request_page, IDictionary<string, string> set, out string serializeStr)
        {
            set.Add("totalPages", totalPages.ToString());
            set.Add("data", dataJson);
            serializeStr = JsonConvert.SerializeObject(set);
            SetCacheOnRedis<string>(EntityBag, TypePage, request_page, LoginType, serializeStr);
        }


        [HttpGet]
        public IActionResult ChangePage([FromQuery] string action,[FromQuery] int request_page)
        {
            IDictionary<string, string> set = new Dictionary<string, string>();
            set.Add("action", action);
            UserInfo? user = null;
            string? keyStr = string.Empty;
            string? cache = string.Empty;
            string? serializeStr = string.Empty;
            switch (action)
            {
                case "sender":
                    //MySession.WriteSession("senderPage", senderPage);
                    int? senderRows = Sess.GetInt32("senderRows");
                    cache = GetCacheFromRedis<string>(EntityBag, TypePage, request_page, LoginType);
                    if (!string.IsNullOrEmpty(cache))
                    {
                        return Json(cache);
                    }
                    else
                    {
                        user = GetObjectFromSession<UserInfo>("detail");
                        if (user == null || request_page == null || senderRows == null) return Json(JsonConvert.SerializeObject(set));
                        (var senderTotalPages, var senderBagList) = _impl.GetSenderList(user.UserName, user.Phone, senderRows.Value, request_page);
                        SetInt32InSession("senderTotalPages", senderTotalPages);
                        FillSetAndSaveCache(senderTotalPages, JsonConvert.SerializeObject(_mapper.Map<IList<BagDTO>>(senderBagList)), request_page, set, out serializeStr);
                        return Json(serializeStr);
                    }

                //return Json(JsonConvert.SerializeObject(senderBagList));
                case "getter":

                    //MySession.WriteSession("getterPage", getterPage);
                    int? getterRows = GetInt32FromSession("getterRows");
                    cache = GetCacheFromRedis<string>(EntityBag, TypePage, request_page, LoginType);
                    if (!string.IsNullOrEmpty(cache))
                    {
                        return Json(cache);
                    }
                    else
                    {
                        user = GetObjectFromSession<UserInfo>("detail");
                        if (user == null || getterRows == null) return Json(JsonConvert.SerializeObject(set));
                        (var getterTotalPages, var getterBagList) = _impl.GetGetterList(user.UserName, user.Phone, getterRows.Value, request_page);
                        SetInt32InSession("getterTotalPages", getterTotalPages);
                        FillSetAndSaveCache(getterTotalPages, JsonConvert.SerializeObject(_mapper.Map < IList < BagDTO >> (getterBagList)), request_page, set, out serializeStr);
                        return Json(serializeStr);
                    }

                case "total":
                    //MySession.WriteSession("bagPage", page);
                    int? rows = GetInt32FromSession("bagRows");
                    cache = GetCacheFromRedis<string>(EntityBag, TypePage, request_page, LoginType);
                    if (!string.IsNullOrEmpty(cache))
                    {
                        return Json(cache);
                    }
                    else
                    {
                        if (request_page == null || rows == null) return Json(JsonConvert.SerializeObject(set));
                        (var bagTotalPages, var bagList) = _impl.GetList(rows.Value, request_page);
                        SetInt32InSession("bagTotalPages", bagTotalPages);
                        FillSetAndSaveCache(bagTotalPages, JsonConvert.SerializeObject(_mapper.Map<IList<BagDTO>>(bagList)), request_page, set, out serializeStr);

                        return Json(serializeStr);
                    }

                default:
                    break;
            }
            return Json(0);

        }


        public IActionResult BagManage()
        {


            //switch (LoginType)
            //{
            //    case "用户":

            //            UserInfo detail = MySession.GetSession_UserInfo("detail");
            //            int senderRows = Convert.ToInt16(MySession.GetSession("senderRows"));
            //            int senderPage = Convert.ToInt16(MySession.GetSession("senderPage"));
            //            int getterRows = Convert.ToInt16(MySession.GetSession("getterRows"));
            //            int getterPage = Convert.ToInt16(MySession.GetSession("getterPage"));
            //        (var total_nums, var ans) = _impl.GetList(detail.UserName, detail.Phone, senderRows, senderPage, getterRows, getterPage);
            //            //ViewBag.SenderBagList = ans[0];
            //        //MySession.WriteSession("senderTotalPages", total_nums[0]);
            //            //ViewBag.GetterBagList = ans[1];
            //        //MySession.WriteSession("getterTotalPages", total_nums[1]);
            //        return PartialView();
            //    case "管理员":
            //    case "快递员":
            //        int rows = Convert.ToInt16(MySession.GetSession("bagRows"));
            //        int page = Convert.ToInt16(MySession.GetSession("bagPage"));
            //        (var totalPages,var data) = _impl.GetList(rows, page);
            //        MySession.WriteSession("bagTotalPages", totalPages);
            //        ViewBag.BagList = data;
            //        return PartialView();
            //    default:
            //        break;
            //}
            //return PartialView(_impl.GetList());
            return PartialView();
        }
        public IActionResult BagRegister()
        {

            switch (LoginType)
            {
                case "用户":
                    return PartialView(GetObjectFromSession<UserInfo>("detail"));
                case "管理员":
                case "快递员":
                    return RedirectToAction("Index", "Home");
                default:
                    break;
            }

            return PartialView();
        }




        [HttpGet]
        public IActionResult GetItemByID([FromQuery] BagDTO entity)
        {
            //string get = MyRequest.GetQueryString();
            //Task obj = tool.DeserializeObject(get) as Task;
            var result = _impl.GetItemByID(entity.BagId);
            string seri = JsonConvert.SerializeObject(_mapper.Map<BagDTO> (result));
            return Json(seri);
        }
        [HttpPost]
        public async Task<IActionResult> Delete([FromForm] BagDTO entity)
        {
            string bagID = entity.BagId;
            if (_impl.DeleteBagInfo(bagID) == true)
            {
                if (LoginType.Equals("用户"))
                {
                    await MqSender.SendMessage(new QueueMessage()
                    {
                        Action = QueueMessage.ActionType.BAG_DELETE,
                        Bag = new Bag() { BagId = bagID },
                        User = new UserInfo() { Id = UserId }
                    }, Resource.CompanyBagRoute);
                }
                else
                {
                    int? id = _impl.GetSenderUserIDByBagID(bagID);
                    if (id != null)
                    {
                        await MqSender.SendMessage(new QueueMessage()
                        {
                            Action = QueueMessage.ActionType.BAG_DELETE,
                            Bag = new Bag() { BagId = bagID },
                            User = new UserInfo() { Id = id.Value }
                        }, Resource.CustomerBagRoute);

                    }

                }
                //删除成功
                RemoveRedisCacheEntity(EntityBag, TypePage, LoginType);
                return Json(1);
            }
            //删除失败
            return Json(0);
        }

        [HttpPost]
        public async Task<IActionResult> Update([FromForm] BagDTO entity)
        {
            //var tool = new JavaScriptSerializer();
            //string get = MyRequest.GetQueryString();
            //Task_Update obj = tool.DeserializeObject(get) as Task_Update;
            Bag update_item = _mapper.Map<Bag>(entity);
            int? id = null;
            switch (entity.Action)
            {
                case "delivery_begin":
                    update_item.BagId = Convert.ToString(Request.Form["Id"]).ToString().Trim();
                    update_item.UpdateTime = DateTime.Now;
                    if (_impl.DeliveryBag(update_item.BagId, update_item))
                    {
                        id = GetInt32FromSession("userID");
                        if (LoginType.Equals("用户"))
                        {
                            if (id != null)
                            {
                                await MqSender.SendMessage(new QueueMessage()
                                {
                                    Action = QueueMessage.ActionType.BAG_UPDATE,
                                    Bag = update_item,
                                    User = new UserInfo() { Id = id.Value }
                                }, Resource.CompanyBagRoute);
                            }

                        }
                        else
                        {
                            id = _impl.GetSenderUserIDByBagID(update_item.BagId);
                            if (id != null)
                            {
                                await MqSender.SendMessage(new QueueMessage()
                                {
                                    Action = QueueMessage.ActionType.BAG_UPDATE,
                                    Bag = update_item,
                                    User = new UserInfo() { Id = id.Value }
                                }, Resource.CustomerBagRoute);
                            }
                        }
                        RemoveRedisCacheEntity(EntityBag, TypePage, LoginType);
                        return Json(1);
                    }
                    break;
                case "delivery_finish":
                    update_item.BagId = Convert.ToString(Request.Form["Id"]);
                    update_item.ArriveDate = update_item.UpdateTime = DateTime.Now;
                    if (_impl.FinishDeliveryingBag(update_item.BagId, update_item))
                    {
                        if (LoginType.Equals("用户"))
                        {
                            id = GetInt32FromSession("userID");
                            if (id != null)
                            {
                                await MqSender.SendMessage(new QueueMessage()
                                {
                                    Action = QueueMessage.ActionType.BAG_UPDATE,
                                    Bag = update_item,
                                    User = new UserInfo() { Id = id.Value }
                                }, Resource.CompanyBagRoute);
                            }

                        }
                        else
                        {
                            id = _impl.GetSenderUserIDByBagID(update_item.BagId);
                            if (id != null)
                            {
                                await MqSender.SendMessage(new QueueMessage()
                                {
                                    Action = QueueMessage.ActionType.BAG_UPDATE,
                                    Bag = update_item,
                                    User = new UserInfo() { Id = id.Value }
                                }, Resource.CustomerBagRoute);
                            }
                        }
                        RemoveRedisCacheEntity(EntityBag, TypePage, LoginType);
                        return Json(1);
                    }

                    break;
                case "update":
                    //update_item.BagId = Convert.ToString(Request.Form["Id"]).ToString().Trim();
                    ////update_item.SendDate = Convert.ToDateTime(Request.Form["SendDate"]);
                    //update_item.GetterName = Convert.ToString(Request.Form["GetterName"]).ToString().Trim();
                    //update_item.GetterPhone = Convert.ToString(Request.Form["GetterPhone"]).ToString().Trim();
                    //update_item.GetterAddress = Convert.ToString(Request.Form["GetterAddress"]).ToString().Trim();
                    //update_item.SenderName = Convert.ToString(Request.Form["SenderName"]).ToString().Trim();
                    //update_item.SenderPhone = Convert.ToString(Request.Form["SenderPhone"]).ToString().Trim();
                    //update_item.SenderAddress = Convert.ToString(Request.Form["SenderAddress"]).ToString().Trim();
                    //update_item.SendInfo = Convert.ToString(Request.Form["SendInfo"]).ToString().Trim();
                    update_item.UpdateTime = DateTime.Now;
                    if (_impl.UpdateBag(update_item.BagId, update_item))
                    {
                        if (LoginType.Equals("用户"))
                        {
                            id = GetInt32FromSession("userID");
                            if (id != null)
                            {
                                await MqSender.SendMessage(new QueueMessage()
                                {
                                    Action = QueueMessage.ActionType.BAG_UPDATE,
                                    Bag = update_item,
                                    User = new UserInfo() { Id = id.Value }
                                }, Resource.CompanyBagRoute);
                            }
                        }
                        else
                        {
                            id = _impl.GetSenderUserIDByBagID(update_item.BagId);
                            if (id != -1)
                            {
                                await MqSender.SendMessage(new QueueMessage()
                                {
                                    Action = QueueMessage.ActionType.BAG_UPDATE,
                                    Bag = update_item,
                                    User = new UserInfo() { Id = id.Value }
                                }, Resource.CustomerBagRoute);
                            }
                        }
                        RemoveRedisCacheEntity(EntityBag, TypePage, LoginType);
                        return Json(1);
                    }
                    break;
                default:
                    break;
            }


            //string get = MyRequest.GetQueryString();
            //Task obj = tool.DeserializeObject(get) as Task;

            return Json(0);
        }


        [HttpPost]
        public async Task<IActionResult> Add([FromForm] BagDTO entity)
        {

            Bag bag = _mapper.Map<Bag>(entity);
            bag.Id = 0;
            bag.SendDate = DateTime.Now;
            bag.BagId = "8888" + DateTime.Now.ToString("yyyyMMddhhmmss");
            //bag.GetterName = Request.Form["GetterName"];
            //bag.GetterPhone = Request.Form["GetterPhone"];
            //bag.GetterAddress = Request.Form["GetterAddress"];
            //bag.SenderName = Request.Form["SenderName"];
            //bag.SenderPhone = Request.Form["SenderPhone"];
            //bag.SenderAddress = Request.Form["SenderAddress"];
            //bag.SendInfo = Request.Form["SendInfo"];
            bag.ArriveInfo = "运输中";
            bag.AddTime = DateTime.Now;
            //bag.ArriveInfo =Request.Form["ArriveInfo"];
            if (!_impl.Add(bag)) return Json(0);
            else
            {
                await MqSender.SendMessage(new QueueMessage() { Action = QueueMessage.ActionType.BAG_REGISTRER, Bag = bag, User = new UserInfo() { Id = GetInt32FromSession("userID").Value } }
, Resource.CompanyBagRoute);
                RemoveRedisCacheEntity(EntityBag, TypePage, LoginType);
                return Json(1);
            }

        }



    }
}